import React, { useState, useEffect } from "react";

import styles from "./Auth.module.css";

import {
  Select,
  Input,
  Table,
  Space,
  Button,
  Pagination,
  Modal,
  message,
} from "antd";

import { SearchOutlined } from "@ant-design/icons";

import axios from "../../../http/index";

import { useNavigate } from "react-router-dom";

const Index = () => {
  const [searchInput, setSearchInput] = useState("");
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [department, setDepartment] = useState(0);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  // 创建权限
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [managerName, setManagerName] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phoneNumber, setPhoneNumber] = useState(null);
  const [role, setRole] = useState("选择角色");
  const [createDe, setCreateDe] = useState("选择部门");
  const [superior, setSuperior] = useState("选择上级");
  const [pwd, setPwd] = useState("");

  const navigate = useNavigate();

  // 表头
  const columns = [
    {
      title: "账号",
      dataIndex: "username",
      align: "center",
    },
    {
      title: "手机号",
      dataIndex: "phoneNumber",
      align: "center",
    },
    {
      title: "所属部门",
      dataIndex: "department",
      align: "center",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      align: "center",
    },
    {
      title: "最后登录",
      dataIndex: "lastLogin",
      align: "center",
    },
    {
      title: "状态",
      dataIndex: "state",
      align: "center",
    },
    {
      title: "操作",
      dataIndex: "action",
      align: "center",
      render: (_, record) => (
        <Space size="middle">
          <Button
            onClick={() => {
              results(record.key);
            }}
          >
            业绩
          </Button>
          <Button
            onClick={() => {
              range(record.key);
            }}
          >
            区域
          </Button>
          <Button>编辑</Button>
          <Button>删除</Button>
        </Space>
      ),
    },
  ];

  // 获取数据
  useEffect(() => {
    setLoading(true);
    axios({
      url: "/auth/getList",
      method: "GET",
      params: {
        currentPage: 1,
      },
    })
      .then((res) => {
        console.log(res);
        if (res.data.code === "200") {
          setList(res.data.data);
          setTotal(res.data.total);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  // 处理数据
  const formateList = list.map((item) => {
    if (item.department === 1) {
      item.department = "运营部";
    } else if (item.department === 2) {
      item.department = "推广部";
    } else {
      item.department = "客服部";
    }
    if (item.state === 0) {
      item.state = "启动";
    } else {
      item.state = "关闭";
    }

    return item;
  });

  const data = [...formateList];

  // 选择部门
  const handleSelectChange = (value) => {
    setDepartment(value);
    setLoading(true);
    axios({
      url: "/auth/getList",
      method: "GET",
      params: {
        department: value,
        search: searchInput,
      },
    })
      .then((res) => {
        if (res.data.code === "200") {
          console.log("------", res);
          setList(res.data.data);
          setTotal(res.data.total);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  // 输入框搜索
  const search = () => {
    setLoading(true);
    axios({
      url: "/auth/getList",
      method: "GET",
      params: {
        department,
        search: searchInput,
      },
    })
      .then((res) => {
        if (res.data.code === "200") {
          setList(res.data.data);
          setTotal(res.data.total);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  // const rowSelection = {
  //   onChange: (selectedRowKeys, selectedRows) => {
  //     console.log(
  //       `selectedRowKeys: ${selectedRowKeys}`,
  //       "selectedRows: ",
  //       selectedRows
  //     );
  //   },
  //   getCheckboxProps: (record) => ({
  //     disabled: record.name === "Disabled User",
  //     // Column configuration not to be checked
  //     name: record.name,
  //   }),
  // };

  // 分页
  const pageChange = (page) => {
    setLoading(true);
    console.log(page);
    setCurrentPage(page);
    axios({
      url: "/auth/getList",
      method: "GET",
      params: {
        currentPage: page,
      },
    })
      .then((res) => {
        console.log(res);
        if (res.data.code === "200") {
          setList(res.data.data);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  // 模态框
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    if (
      managerName &&
      name &&
      email &&
      phoneNumber &&
      role &&
      createDe &&
      pwd
    ) {
      setIsModalOpen(false);
      setManagerName("");
      setName("");
      setEmail("");
      setPhoneNumber(null);
      setRole("选择角色");
      setCreateDe("选择部门");
      setSuperior("选择上级");
      setPwd("");

      axios({
        url: "/auth/create",
        method: "GET",
        params: {
          managerName,
          name,
          email,
          phoneNumber,
          role,
          createDe,
          superior,
          pwd,
        },
      })
        .then((res) => {
          if (res.data.code === "200") {
            message.success(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      message.warning("必填信息未填全");
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setManagerName("");
    setName("");
    setEmail("");
    setPhoneNumber(null);
    setRole("选择角色");
    setCreateDe("选择部门");
    setSuperior("选择上级");
    setPwd("");
  };

  // 操作按钮
  // 业务按钮
  const results = (value) => {
    console.log(value);
    navigate(`/system/results/${value}`);
  };

  // 区域按钮
  const range = (value) => {
    console.log(value);
  };

  return (
    <div className={styles.auth}>
      <Modal
        title="新建管理"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        bodyStyle={{
          height: "550px",
        }}
        width="550px"
        okText="保存"
        cancelText="取消"
      >
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>管理员名称：</span>
          </div>
          <Input
            showCount
            maxLength={50}
            onChange={(e) => {
              setManagerName(e.target.value);
            }}
            value={managerName}
            className={styles.createInput}
            placeholder="输入管理员名称"
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>管理员姓名：</span>
          </div>
          <Input
            showCount
            maxLength={50}
            onChange={(e) => {
              setName(e.target.value);
            }}
            value={name}
            className={styles.createInput}
            placeholder="输入管理员姓名"
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>邮箱地址：</span>
          </div>
          <Input
            onChange={(e) => {
              setEmail(e.target.value);
            }}
            value={email}
            className={styles.createInput}
            placeholder="输入管理员邮箱，为了接收消息"
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>手机号码：</span>
          </div>
          <Input
            onChange={(e) => {
              setPhoneNumber(e.target.value);
            }}
            value={phoneNumber}
            className={styles.createInput}
            placeholder="输入管理员手机，为了接收消息"
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>所属角色：</span>
          </div>
          <Select
            value={role}
            style={{
              width: 120,
            }}
            onChange={(e) => {
              setRole(e);
            }}
            options={[
              {
                value: 0,
                label: "运营人员",
              },
              {
                value: 1,
                label: "推广人员",
              },
              {
                value: 2,
                label: "客服人员",
              },
              {
                value: 3,
                label: "财务人员",
              },
            ]}
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>所属部门：</span>
          </div>
          <Select
            value={createDe}
            style={{
              width: 120,
            }}
            onChange={(e) => {
              setCreateDe(e);
            }}
            options={[
              {
                value: 0,
                label: "运营部",
              },
              {
                value: 1,
                label: "推广部",
              },
              {
                value: 2,
                label: "客服部",
              },
              {
                value: 3,
                label: "财务部",
              },
            ]}
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span>上级：</span>
          </div>
          <Select
            value={superior}
            style={{
              width: 120,
            }}
            onChange={(e) => {
              setSuperior(e);
            }}
            options={[
              {
                value: 0,
                label: "上级名称",
              },
              {
                value: 1,
                label: "上级名称",
              },
              {
                value: 2,
                label: "上级名称",
              },
              {
                value: 3,
                label: "上级名称",
              },
            ]}
          />
        </div>
        <div className={styles.modal_row}>
          <div className={styles.keys}>
            <span className={styles.xing}>*</span>
            <span>登录密码：</span>
          </div>
          <Input
            onChange={(e) => {
              setPwd(e.target.value);
            }}
            value={pwd}
            className={styles.createInput}
            placeholder="输入管理员登录密码，推荐数字+符号6位数以上的密码"
          />
        </div>
      </Modal>
      <div className={styles.title}>
        <span>权限管理</span>
        <div className={styles.border_row}></div>
      </div>
      <hr className={styles.hr} />
      <div className={styles.header}>
        <div>
          <Select
            defaultValue="0"
            style={{
              width: 144,
            }}
            onChange={handleSelectChange}
            options={[
              {
                value: "0",
                label: "全部",
              },
              {
                value: "1",
                label: "运营部",
              },
              {
                value: "2",
                label: "推广部",
              },
              {
                value: "3",
                label: "客服部",
              },
            ]}
          />
          <Input
            placeholder="账号名称/手机号"
            value={searchInput}
            onChange={(e) => {
              setSearchInput(e.target.value);
            }}
            onPressEnter={search}
            className={styles.searchInput}
            suffix={<SearchOutlined />}
          />
        </div>
        <div>
          <Button type="primary" onClick={showModal}>
            创建权限
          </Button>
        </div>
      </div>
      <div className={styles.content}>
        <div className={styles.table_box}>
          <Table
            rowSelection={{
              type: "checkbox",
              // ...rowSelection,
            }}
            columns={columns}
            dataSource={data}
            pagination={false}
            loading={loading}
          />
        </div>
        <div className={styles.page_box}>
          <Pagination
            current={currentPage}
            total={total}
            showTotal={(total) => `合计 ${total} 条`}
            onChange={(page) => {
              pageChange(page);
            }}
          />
        </div>
      </div>
    </div>
  );
};

export default Index;
